import kivy
kivy.require('1.2.0')

from Queue import Queue, Empty
from kivy.app import App
from kivy.base import EventLoop
from kivy.logger import Logger, formatter_message, ColoredFormatter, \
	ConsoleHandler, LoggerHistory, FileHandler, LogFile
from kivy.resources import resource_add_path
from kivy.uix.floatlayout import FloatLayout
from nmjeditor.screens.screen_factory import ScreenFactory
import os.path
import sys


class NmjEditor(App):
	def __init__(self):
		super(NmjEditor, self).__init__()
		resource_add_path(self.__get_resources_path())
		self.queue = Queue()
		self.factory = ScreenFactory(self.queue, EventLoop.window.canvas)
		self.controller = self.factory.get_controller()
		self.__current = None
		EventLoop.window.bind(on_draw=self._check_event)

	def _check_event(self, *arg, **kwargs):
		try:
			event = self.queue.get(False)
		except Empty:
			pass
		else:
			method = getattr(self.factory, event.method, None)
			if method:
				try:
					Logger.info("Running %s(%s, %s)", event.method, event.args, event.kwargs)
					method(*event.args, **event.kwargs)
				except:
					Logger.exception("Problem when running command %s", method)
			else:
				Logger.error("Method %s not found on %s", event.method, self.factory.current_screen.__class__.__name__)

	def __get_resources_path(self):
		res_dir = os.path.join(os.path.dirname(__file__), "resources")
		if not os.path.isdir(res_dir):
			res_dir = os.path.join("usr", "share", "nmjeditor", "resources")
		return res_dir

	def put(self, event):
		method = getattr(self, event.method, None)
		if method:
			try:
				Logger.info("Running %s(%s, %s)", event.method, event.args, event.kwargs)
				method(*event.args, **event.kwargs)
			except:
				Logger.exception("Problem when running command %s", method)
		else:
			Logger.error("Method %s not found on %s", event.method, self.__class__.__name__)

	def change_screen(self, screenname, *args, **kwargs):
		screen = self.factory.getScreen(screenname, self, *args, **kwargs)
		if self.__current:
			self.root_layout.remove_widget(self.__current)
		self.root_layout.add_widget(screen)
		self.__current = screen

	def on_start(self):
		try:
			self.factory.set_screen("Main")
			self.controller.get_shows()
		except :
			Logger.exception("Error on start")

	def on_stop(self):
		self.factory.stop()

	def build(self):
		self.root_layout = FloatLayout()
		self.factory.set_root(self.root_layout)
		return self.root_layout


if __name__ in ('__android__', '__main__'):
	from functools import partial
	import logging
	Logger.handlers=[]
	use_color = os.name != 'nt'
	color_fmt = formatter_message('%(threadName)s [%(levelname)-18s] %(message)s', use_color)
	formatter = ColoredFormatter(color_fmt, use_color=use_color)
	console = ConsoleHandler()
	console.setFormatter(formatter)
	Logger.addHandler(console)
	Logger = logging.getLogger('nmj')
	Logger.logfile_activated = False
	Logger.trace = partial(Logger.log, logging.TRACE)

	# add default kivy logger
	Logger.addHandler(LoggerHistory())
	Logger.addHandler(FileHandler())

	# Use the custom handler instead of streaming one.
	if hasattr(sys, '_kivy_logging_handler'):
		Logger.addHandler(getattr(sys, '_kivy_logging_handler'))
	else:
		use_color = os.name != 'nt'
		color_fmt = formatter_message('%(threadName)s [%(levelname)-18s] %(message)s', use_color)
		formatter = ColoredFormatter(color_fmt, use_color=use_color)
		console = ConsoleHandler()
		console.setFormatter(formatter)
		Logger.addHandler(console)

	# install stderr handlers
	sys.stderr = LogFile('stderr', Logger.warning)
	NmjEditor().run()


